<template>
  <view class="bg-slate-100 w-screen h-10"></view>
  <view class="bg-slate-200 w-screen h-10"></view>
  <view class="bg-slate-300 w-screen h-10"></view>
  <view class="bg-slate-400 w-screen h-10"></view>
  <view class="bg-slate-500 w-screen h-10"></view>
  <view class="bg-slate-600 w-screen h-10"></view>
  <view class="bg-slate-700 w-screen h-10"></view>
  <view>
    <view style="margin: 20rpx 0">
      <nut-button @click="connectweb" block type="primary">连接 WebSocket</nut-button>
    </view>
    <view style="margin: 20rpx 0">
      <nut-button @click="sendmsg" block type="success" :disabled="!webstore.isConnected">发送消息</nut-button>
    </view>
  </view>
  <view class="title">
    <nut-form-item label-width="80rpx" label="消息" label-align="center">
      <nut-input v-model="message" placeholder="请输入文本" :border="false"></nut-input>
    </nut-form-item>
  </view>
  <view>
    <div v-for="(item, index) in webstore.arr" :key="index">{{ item.name }}---{{ item.message }}</div>
  </view>
</template>

<script setup>
import { websocketStore } from "@/store";

import { ref, onMounted, onBeforeUnmount } from "vue";
let arr = ref([]);
const webstore = websocketStore();

const socket = ref(null);
const message = ref("");
const isConnected = ref(false);
let userarr = ref(["小华", "小明", "小红花"]);

const connectweb = () => {
  webstore.connectWebSocket("ws://localhost:8080");
};

// 发送消息
const sendmsg = () => {
  const obj = {
    message: message.value,
    name: userarr.value[Math.floor(Math.random() * userarr.value.length)],
  };
  webstore.sendWebSocketMessage(obj);
};

// 在组件挂载时自动连接 WebSocket
onMounted(() => {
  // connectWebSocket();
});

// 在组件卸载前关闭 WebSocket
onBeforeUnmount(() => {
  if (webstore.socket.value) {
    webstore.socket.value.close();
  }
});
</script>

<style scoped>
.title :deep(.nut-cell__title) {
  min-width: 60px;
}
</style>
